package com.nf.practice.exportExcel;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

// 司法大数据公司明细导出
public class SfCompanyDataExportFinal {

    private final String dmsUrl = "http://172.16.10.5:31314/service";
//private final String dmsUrl = "http://192.168.40.49:1688/service";

    @Test
    public void batchExport2() {

//        String fileName = "E:/SFDSJ/sffile.xlsx";
        String fileName = "E:/SFDSJ/23年核销数据明细导出.xlsx";

        // 读取到的数据
        List<SfFile> list = EasyExcel.read(fileName)
                .head(SfFile.class)
                .sheet()
                .doReadSync();

//        List<SfFile> list = new ArrayList<>();
//        SfFile sfFile = new SfFile();
//        sfFile.setAppNo("1234567");
//        sfFile.setName("广州市网商小额贷款有限责任公司");
//        list.add(sfFile);

        List<SfImplementCountData> dataList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            String appNo = list.get(i).getAppNo();
            String name = list.get(i).getName();
            String idNo = list.get(i).getIdNo();
            System.out.println(appNo);
            System.out.println(idNo);
            System.out.println(name);

            // 2、调用dms
            // 公开模型
            JSONObject ss01EntJson = getSourceData(appNo, idNo, name, "ENTOUT");
            // 失信模型
            JSONObject sxJsonData = getSourceData(appNo, idNo, name,"SXBZXR");
            // 限高模型
            JSONObject xgJsonData = getSourceData(appNo, idNo, name,"XGBZXR");

            try {
                // 公开模型处理
                // SS01本人公开模型
                Map<String, Object> map = dataAnalysis(ss01EntJson);
                List<Map<String, Object>> implementCasesData = (List<Map<String, Object>>) map.get("implementCasesData");
                if (!CollectionUtils.isEmpty(implementCasesData)) {
                    for (int j = 0; j < implementCasesData.size(); j++) {
                        Map<String, Object> finalMap = implementCasesData.get(j);
                        SfImplementCountData data = new SfImplementCountData();
                        data.setAppNo(appNo).setName(name).setIdNo(idNo).setType("公开模型")
                                .setN_ajlx((String) finalMap.get("n_ajlx"))
                                .setC_ah((String) finalMap.get("c_ah"))
                                .setC_ah_ys((String) finalMap.get("c_ah_ys"))
                                .setC_ah_hx((String) finalMap.get("c_ah_hx"))
                                .setN_ajbs((String) finalMap.get("n_ajbs"))
                                .setN_jbfy((String) finalMap.get("n_jbfy"))
                                .setN_jbfy_cj((String) finalMap.get("n_jbfy_cj"))
                                .setC_ssdy((String) finalMap.get("c_ssdy"))
                                .setD_larq((String) finalMap.get("d_larq"))
                                .setN_ajjzjd((String) finalMap.get("n_ajjzjd"))
                                .setN_laay((String) finalMap.get("n_laay"))
                                .setN_sqzxbdje((String) finalMap.get("n_sqzxbdje"))
                                .setD_jarq((String) finalMap.get("d_jarq"))
                                .setN_jaay((String) finalMap.get("n_jaay"))
                                .setN_jabdje((String) finalMap.get("n_jabdje"))
                                .setN_jabdje_gj((String) finalMap.get("n_jabdje_gj"))
                                .setN_sjdwje((String) finalMap.get("n_sjdwje"))
                                .setN_wzxje((String) finalMap.get("n_wzxje"))
                                .setN_jafs((String) finalMap.get("n_jafs"))
                                .setN_ssdw((String) finalMap.get("n_ssdw"))
                                .setC_gkws_id((String) finalMap.get("c_gkws_id"))
                                .setC_gkws_glah((String) finalMap.get("c_gkws_glah"))
                                .setC_gkws_dsr((String) finalMap.get("c_gkws_dsr"))
                                .setC_gkws_pjjg((String) finalMap.get("c_gkws_pjjg"))
                                .setDsrDatas((String) finalMap.get("c_dsrxx"));
                        dataList.add(data);
                    }
                }


                // 失信模型处理
                // SS01本人失信模型
                JSONObject ss01SxData = null;
                if (null != sxJsonData && !sxJsonData.isEmpty()) {
                    ss01SxData = sxJsonData.getJSONObject("data");
                }
                if (null != ss01SxData && !ss01SxData.isEmpty()) {
                    JSONObject ss01SxRes = ss01SxData.getJSONObject("data");
                    if (null != ss01SxRes && !ss01SxRes.isEmpty()) {
                        JSONArray sxbzxrArr = ss01SxRes.getJSONArray("sxbzxr");
                        if (!CollectionUtils.isEmpty(sxbzxrArr)) {
                            for (int k = 0; k < sxbzxrArr.size(); k++) {
                                JSONObject json = sxbzxrArr.getJSONObject(k);
                                if (null != json && !json.isEmpty()) {
                                    SfImplementCountData data = new SfImplementCountData();
                                    String id = json.getString("id");
                                    String xb = json.getString("xb");
                                    String zzjgdm = json.getString("zzjgdm");
                                    String qyfr = json.getString("qyfr");
                                    String zxfy = json.getString("zxfy");
                                    String sf = json.getString("sf");
                                    String zxyjwh = json.getString("zxyjwh");
                                    String larq = json.getString("larq");
                                    String ah = json.getString("ah");
                                    String zxyjdw = json.getString("zxyjdw");
                                    String yw = json.getString("yw");
                                    String lxqk = json.getString("lxqk");
                                    String xwqx = json.getString("xwqx");
                                    String fbrq = json.getString("fbrq");
                                    String pjje_gj = json.getString("pjje_gj");
                                    data.setAppNo(appNo).setName(name).setIdNo(idNo)
                                            .setType("失信")
                                            .setId(id)
                                            .setXb(xb)
                                            .setZzjgdm(zzjgdm)
                                            .setQyfr(qyfr)
                                            .setZxfy(zxfy)
                                            .setSf(sf)
                                            .setZxyjwh(zxyjwh)
                                            .setLarq(larq)
                                            .setAh(ah)
                                            .setZxyjdw(zxyjdw)
                                            .setYw(yw)
                                            .setLxqk(lxqk)
                                            .setXwqx(xwqx)
                                            .setFbrq(fbrq)
                                            .setPjje_gj(pjje_gj);
                                    dataList.add(data);
                                }
                            }
                        }
                    }
                }

                // 限高模型处理
                // SS01本人限高模型
                JSONObject ss01XgData = null;
                if (null != xgJsonData && !xgJsonData.isEmpty()) {
                    ss01XgData = xgJsonData.getJSONObject("data");
                }
                if (null != ss01XgData && !ss01XgData.isEmpty()) {
                    JSONObject ss01XgRes = ss01XgData.getJSONObject("data");
                    if (null != ss01XgRes && !ss01XgRes.isEmpty()) {
                        JSONArray xgbzxrArr = ss01XgRes.getJSONArray("xgbzxr");
                        if (!CollectionUtils.isEmpty(xgbzxrArr)) {
                            for (int m = 0; m < xgbzxrArr.size(); m++) {
                                SfImplementCountData data = new SfImplementCountData();
                                JSONObject json = xgbzxrArr.getJSONObject(m);
                                if (null != json && !json.isEmpty()) {
                                    String qymc = json.getString("qymc");
                                    String qyfr = json.getString("qyfr");
                                    String id = json.getString("id");
                                    String zxfy = json.getString("zxfy");
                                    String ah = json.getString("ah");
                                    String larq = json.getString("larq");
                                    String fbrq = json.getString("fbrq");
                                    data.setAppNo(appNo).setName(name).setIdNo(idNo)
                                            .setType("限高")
                                            .setQymc(qymc)
                                            .setId(id)
                                            .setQyfr(qyfr)
                                            .setZxfy(zxfy)
                                            .setLarq(larq)
                                            .setAh(ah)
                                            .setFbrq(fbrq);
                                    dataList.add(data);
                                }
                            }
                        }
                    }
                }

                System.out.println(idNo + "-" + name + "处理完成!");

            } catch (Exception e) {
                System.out.println(idNo + "-" + name + "处理异常!");
            }

        }

        ExcelWriter writer = ExcelUtil.getWriter(new File("E:/SFDSJ/20240409司法大数据明细导出.xlsx"));
        if(!CollectionUtils.isEmpty(dataList)){
            writer.setSheet(0).write(dataList);
            writer.flush();
        }

    }

    private Map<String, Object> dataAnalysis(JSONObject ss01EntJson) {
        Map<String, Object> map = new HashMap<>();
        JSONObject ss01EntData = null;
        if (null != ss01EntJson && !ss01EntJson.isEmpty()) {
            ss01EntData = ss01EntJson.getJSONObject("data");
        }
        if (null != ss01EntData && !ss01EntData.isEmpty()) {
            JSONObject res = ss01EntData.getJSONObject("data");
            if (null != res && !res.isEmpty()) {
                map.put("entoutData", "entoutData");
                getMapData(map,res,"implement");
            }
        }
        return map;
    }

    private void getMapData(Map<String, Object> map, JSONObject res, String key) {
        // civil
        JSONObject json = res.getJSONObject(key);
        if (null != json && !json.isEmpty()) {
            JSONArray cases= json.getJSONArray("cases");
            if (!CollectionUtils.isEmpty(cases)) {
                switch (key) {
                    case ("implement"):
                        map.put("implementCasesData",getCaseDetailData(cases,key));
                        break;
                }
            }

        }
    }

    private List<Map<String, Object>> getCaseDetailData(JSONArray originArr, String key) {
        List<Map<String, Object>> resData = new ArrayList<>();
        for (int i = 0; i < originArr.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            JSONObject json = originArr.getJSONObject(i);
            if (null != json && !json.isEmpty()) {
                switch (key) {
                    case ("implement"):
                        getImplementMap(map,json);
                        break;
                }
                resData.add(map);
            }
        }
        return resData;
    }

    private void getImplementMap(Map<String, Object> map, JSONObject json) {
        map.put("n_ajlx",json.getString("n_ajlx"));
        map.put("c_ah",json.getString("c_ah"));
        map.put("c_ah_ys",json.getString("c_ah_ys"));
        map.put("c_ah_hx",json.getString("c_ah_hx"));
        map.put("n_ajbs",json.getString("n_ajbs"));
        map.put("n_jbfy",json.getString("n_jbfy"));
        map.put("n_jbfy_cj",json.getString("n_jbfy_cj"));

        map.put("c_ssdy",json.getString("c_ssdy"));
        map.put("n_ajjzjd",json.getString("n_ajjzjd"));
        map.put("d_larq",json.getString("d_larq"));

        map.put("n_laay",json.getString("n_laay"));
        map.put("n_sqzxbdje",json.getString("n_sqzxbdje"));
        map.put("d_jarq",json.getString("d_jarq"));
        map.put("n_jaay",json.getString("n_jaay"));
        map.put("n_jabdje",json.getString("n_jabdje"));
        map.put("n_jabdje_gj",json.getString("n_jabdje_gj"));
        map.put("n_sjdwje",json.getString("n_sjdwje"));
        map.put("n_wzxje",json.getString("n_wzxje"));
        map.put("n_jafs",json.getString("n_jafs"));

        map.put("n_ssdw",json.getString("n_ssdw"));
        map.put("c_gkws_id",json.getString("c_gkws_id"));
        map.put("c_gkws_glah",json.getString("c_gkws_glah"));
        map.put("c_gkws_dsr",json.getString("c_gkws_dsr"));
        map.put("c_gkws_pjjg",json.getString("c_gkws_pjjg"));
        getDsrXx(map,json);
    }

    private void getDsrXx(Map<String, Object> map,JSONObject json) {
        JSONArray c_dsrxxArr = json.getJSONArray("c_dsrxx");
//        List<Map<String,Object>> c_dsrxxList = new ArrayList<>();
        List<String> c_dsrxxList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(c_dsrxxArr)) {
            for (int i = 0; i < c_dsrxxArr.size(); i++) {
                JSONObject c_dsrxx = c_dsrxxArr.getJSONObject(i);
                if (c_dsrxx != null && !c_dsrxx.isEmpty()) {
//                    Map<String,Object> c_dsrxxMap = new HashMap<>();
//                    c_dsrxxMap.put("c_mc",c_dsrxx.getString("c_mc"));
//                    c_dsrxxMap.put("n_dsrlx",c_dsrxx.getString("n_dsrlx"));
//                    c_dsrxxMap.put("n_ssdw",c_dsrxx.getString("n_ssdw"));
//                    c_dsrxxList.add(c_dsrxxMap);

                    String dsrXx = c_dsrxx.getString("c_mc") + "/"
                            + c_dsrxx.getString("n_dsrlx") + "/"
                            + c_dsrxx.getString("n_ssdw");
                    c_dsrxxList.add(dsrXx);
                }
            }
        }
        map.put("c_dsrxx",String.join(",", c_dsrxxList));
    }

    public JSONObject getSourceData(String appNo,String idNo,String name, String model) {
        Date date = new Date();
        LocalDateTime startDate = date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime endDate = startDate.plusYears(5); // 在开始日期上加五年得到结束日期
        // 将日期转换为指定格式
        DateTimeFormatter authedFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = startDate.format(authedFormatter);
        String inquiredAuth = "authed:" + startDateStr + "-" + endDate.format(authedFormatter);

        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("app_no", appNo);
        reqMap.put("name", name);
        reqMap.put("id", idNo);
        reqMap.put("inquired_auth", inquiredAuth);
//        reqMap.put("phone", "");
        reqMap.put("cardId", idNo);
        reqMap.put("businessType", "offline");
        reqMap.put("systmeName", "手动");
        reqMap.put("businessScenario", "财务");

        // 2、调用dms
        JSONObject resJson = getSfData(reqMap,model);
        return resJson;
    }

    private JSONObject getSfData(Map<String,Object> reqMap,String model) {
        reqMap.put("model", model);
        String json = JSON.toJSONString(reqMap);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(dmsUrl + "/SS02");
        String resStr = null;
        try {
            StringEntity s = new StringEntity(json, "UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                resStr = EntityUtils.toString(res.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        JSONObject jsonData = new JSONObject();
        if (StringUtils.isNotBlank(resStr)) {
            jsonData = JSONObject.parseObject(resStr);
        }
        return jsonData;
    }

}
